import React, {Component} from "react";
import {Button, Card, Checkbox, Form, Radio, Row, Col} from 'antd';



class QuestionForm extends Component {

  handleSubmit = (e) => {
    e.preventDefault();
    const {onSubmit, form} = this.props;
    form.validateFields((err,values) => {
      if (err) return;
      onSubmit(values);
    });
  }

  render() {
    const {formData,form} = this.props;
    const {getFieldDecorator} = form;
    return (
      <Card>
        <Form onSubmit={this.handleSubmit}>
          {formData.map((item,index) => {
            if(item.type === "single"){
              return(
                <Form.Item key={index} label={`${index+1}、 ${item.label}`}>
                  {getFieldDecorator(item.name,{rules: [{
                      required: true,
                      message: '请选择您的答案',
                    }]})(
                    <Radio.Group>

                      {item.chosen.map(chose => {
                        return(
                          <Row key={chose.value}>
                            <Radio key={chose.value} value={chose.value}> {chose.option}</Radio>
                          </Row>
                        )
                      })}

                    </Radio.Group>
                  )}
                </Form.Item>
              )
            }else{
              return(
                <Form.Item key={index} label={`${index+1}、 ${item.label}`}>
                  {getFieldDecorator(item.name,{rules: [{
                      required: true,
                      message: '请选择您的答案',
                    }]})(
                    <Checkbox.Group style={{ width: '100%'}}>
                      {item.chosen.map(chose => {
                        return(
                          <Row key={chose.value} style={{ padding: 12 }}>
                            <Checkbox key={chose.value} value={chose.value}> {chose.option}</Checkbox>
                          </Row>
                        )
                      })}
                    </Checkbox.Group>
                  )}
                </Form.Item>
              )
            }

          })}

          <Form.Item wrapperCol={{ span: 12}}>
            <Button type="primary" htmlType="submit">
              交卷
            </Button>
          </Form.Item>
        </Form>
      </Card>
    )
  }
}

QuestionForm = Form.create({
  onFieldsChange(props, changedFields) {
    props.onFieldsChange(changedFields);
  },
  mapPropsToFields(props) {
    const {fieldValue, formData} = props;
    let fields = {};
      formData.map(data => {
        fields[data.name] = Form.createFormField({
          ...fieldValue[data.name]
        });
      })
    return fields;
  }
})(QuestionForm);

export default QuestionForm;
